package com.example.dmweb.chat.chatService;

import com.example.dmdomain.ChatFileRepository;
import com.example.dmdomain.SystemChatFileRepository;
import com.example.dmdomain.entity.ChatFile;
import com.example.dmdomain.entity.SystemChatFile;
import com.example.dmweb.chat.chatService.utils.HWOcrUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.persistence.criteria.Predicate;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
@Slf4j
public class ChatGPTFileService {
    @Resource
    private ChatFileRepository chatFileRepository;
    @Resource
    private SystemChatFileRepository systemChatFileRepository;
    public String saveFile(MultipartFile file, String userPhone) {
        try {
            String fileName = file.getOriginalFilename();
            String directoryPath = "/DM_OFFICIAL_WEB/file/" + userPhone + "/";
//        String directoryPath = "D:\\测试PDF文件上传" + userPhone + "\\";

            File directory = new File(directoryPath);

            // 检查目录是否存在，如果不存在则创建目录
            if (!directory.exists()) {
                directory.mkdirs(); // 创建多级目录
            }

            String filePath = directoryPath + fileName;
            File dest = new File(filePath);
            file.transferTo(dest);
        } catch (IOException ex) {
            ex.printStackTrace();
            return "文件保存失败";
        }
        return "文件保存成功";
    }

    public FileUploadResponse fileInfoWarehousing (MultipartFile file,String userPhone,String userId,String systemName) {
        FileUploadResponse fileUploadResponse = new FileUploadResponse();
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            sdf.setTimeZone(TimeZone.getTimeZone("GMT+8"));
            Date date = new Date();
            long timestamp = date.getTime();
            String fileName = file.getOriginalFilename();
            long fileSize = file.getSize();
            String filePath = "/DM_OFFICIAL_WEB/file/"+ userPhone +"/"+ fileName;
//            String filePath = "D:\\测试PDF文件上传"+ userPhone +"/"+ fileName;

            String fileExtension;
            if (fileName.lastIndexOf(".") != -1 && fileName.lastIndexOf(".") != 0) {
                fileExtension = fileName.substring(fileName.lastIndexOf(".")+1);
            } else {
                fileExtension = "未知";
            }
            String fileType = getFileType(fileExtension);
            ChatFile chatFile = new ChatFile();
            Random random = new Random();
            chatFile.setFileId(timestamp + "_" + fileSize+ random.nextInt(100));
            chatFile.setFileName(fileName);
            chatFile.setFileSize(String.valueOf(fileSize));
            chatFile.setUserId(userId);
            chatFile.setFileContent(fileName);
            int oldFileSize = 0;
            String oldFile = "";
            int system = 0;
            if (systemName == null || systemName.isEmpty()) {
                Specification<ChatFile> spec = (root, criteriaQuery, cb) -> {
                    List<Predicate> predicates = new ArrayList<>();
                    predicates.add(cb.equal(root.get("fileName"),fileName));
                    criteriaQuery.where(cb.and(predicates.toArray(new Predicate[0])));
                    criteriaQuery.orderBy(cb.asc(root.get("uploadTime")));
                    return criteriaQuery.getRestriction();
                };
                List<ChatFile> oldFileList = chatFileRepository.findAll(spec);
                oldFileSize = oldFileList.size();
                if (oldFileSize > 0) {
                    oldFile = oldFileList.get(0).getFileId();
                }
                system = 1;
            } else {
                Specification<SystemChatFile> spec = (root, criteriaQuery, cb) -> {
                    List<Predicate> predicates = new ArrayList<>();
                    predicates.add(cb.equal(root.get("fileName"),fileName));
                    criteriaQuery.where(cb.and(predicates.toArray(new Predicate[0])));
                    criteriaQuery.orderBy(cb.asc(root.get("uploadTime")));
                    return criteriaQuery.getRestriction();
                };
                List<SystemChatFile> oldFileList = systemChatFileRepository.findAll(spec);
                oldFileSize = oldFileList.size();
                if (oldFileSize > 0) {
                    oldFile = oldFileList.get(0).getFileId();
                }
                system = 2;
            }

            if (oldFileSize == 0) {
                fileUploadResponse.setFileId(chatFile.getFileId());
            } else {
                fileUploadResponse.setFileId(oldFile);
            }
            fileUploadResponse.setFileName(fileName);
            fileUploadResponse.setFileSize(fileSize/1024 + " KB");
            fileUploadResponse.setFileType(fileType);

//            String[] keywords = {"电费", "账单"};
            if (oldFileSize == 0) {
                File nowFile = new File(filePath);
                File parentDir = nowFile.getParentFile();
                if (parentDir != null && !parentDir.exists()) {
                    parentDir.mkdirs(); // 创建多级目录
                }

                if (!nowFile.exists()) {
                    nowFile.createNewFile();
                }
                try (InputStream stream = Files.newInputStream(nowFile.toPath())) {
                    chatFile.setFileContent(new HWOcrUtil().pic2String(stream, fileType));
                } catch (IOException e) {
                    e.printStackTrace();
                    return fileUploadResponse;
                }
            }

            chatFile.setSessionId(String.valueOf(System.currentTimeMillis()));
            chatFile.setUploadTime(sdf.format(date));
            chatFile.setFilePath(filePath);
            if (system == 1 ) {
                chatFileRepository.save(chatFile);
            } else if (system == 2 ) {
                systemChatFileRepository.save(toSystemChatFile(chatFile,systemName));
            }


            return fileUploadResponse;
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return fileUploadResponse;
    }

    private SystemChatFile toSystemChatFile(ChatFile chatFile,String systemName) {
        SystemChatFile systemChatFile = new SystemChatFile();
        systemChatFile.setFileId(chatFile.getFileId());
        systemChatFile.setFileName(chatFile.getFileName());
        systemChatFile.setFileSize(chatFile.getFileSize());
        systemChatFile.setUserId(chatFile.getUserId());
        systemChatFile.setFileContent(chatFile.getFileContent());
        systemChatFile.setDelState(chatFile.getDelState());
        systemChatFile.setSessionId(chatFile.getSessionId());
        systemChatFile.setUploadTime(chatFile.getUploadTime());
        systemChatFile.setFilePath(chatFile.getFilePath());
        systemChatFile.setSystemName(systemName);
        return systemChatFile;
    }
    public static String getFileType(String fileExtension) {
        String fileType = "";
        switch (fileExtension) {
            case "jpg":
            case "png":
            case "jpeg":
            case "bmp":
            case "tiff":
                fileType = "img";
                break;
            case "pdf":
                fileType = "pdf";
                break;
            default:
                fileType = "未知类型文件";
                break;
        }
        return fileType;
    }
}
